package com.ruoyi.business.utils;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import org.apache.commons.codec.binary.Base64;

import java.security.KeyPair;

public class RSAUtil {
    private static final String publicKey;
    private static final String privateKey;

    static {
        KeyPair pair = SecureUtil.generateKeyPair("RSA");
        publicKey = new String(Base64.encodeBase64(pair.getPublic().getEncoded()));
        privateKey= new String(Base64.encodeBase64((pair.getPrivate().getEncoded())));
    }

    /**
     *
     * @param str 加密前JSONObject->Str数据
     * @return 返回加密后数据
     */
    public static String encrypt(String str){
        return SecureUtil.rsa(privateKey,publicKey).encryptBcd(str, KeyType.PrivateKey);
    }

    /**
     *
     * @param str 加密后的字符串
     * @return
     */
    public static String decrypt (String str){
        return SecureUtil.rsa((String) null,publicKey).decryptStrFromBcd(str, KeyType.PublicKey);
    }
}
